<?php


namespace app\model\partner;


use app\model\config\RecycleModel;
use app\model\config\RegionModel;
use think\Model;
use think\model\concern\SoftDelete;
use zjkal\TimeHelper;

class UserPartnerModel extends Model
{
    use SoftDelete;
    protected $defaultSoftDelete = 0;

    protected $name = 'user_partner';
    protected $autoWriteTimestamp = true;

    protected $hidden = ['password', 'update_time', 'delete_time'];

//    protected $json = ['cart_img'];
//    protected $jsonAssoc = true;

    protected $append = ['birthday_txt', 'age', 'user_type_txt', 'drive_age', 'drive_time_txt'];


    public function setPasswordAttr($value)
    {
        if (!$value) {
            return '';
        }
        return password_hash($value, PASSWORD_DEFAULT);
    }

    public function region()
    {
        return $this->hasOne(RegionModel::class, 'id', 'city')->bind(['city_name' => 'name']);
    }

    public function getBirthdayTxtAttr($value, $data)
    {
        if (!isset($data['birthday'])) {
            return '';
        }
        return date('Y-m-d', $data['birthday']);
    }

    public function getAgeAttr($value, $data)
    {
        if (!isset($data['birthday'])) {
            return '';
        }
        return calculateAge(date('Y-m-d H:i:s', $data['birthday']));
    }

    public static function onBeforeDelete(Model $model)
    {
        $recycleModel = new RecycleModel();
        $data = [
            'uid' => $model->id,
            'type' => 3,
            'title' => $model['username'],
            'mobile' => $model['mobile'],
        ];
        $recycleModel->save($data);
    }

    public function getUserTypeTxtAttr($value, $data)
    {
        if (!isset($data['user_type'])) {
            return '';
        }
        if ($data['user_type'] == 0) {
            return '陪驾教练';
        }
        if ($data['user_type'] == 1) {
            return '验车师';
        }
        return '陪驾教练+验车师';
    }

    public function getDriveAgeAttr($value, $data)
    {
        if (!isset($data['drive_time'])) {
            return 0;
        }
        return calculateAge(date('Y-m-d H:i:s', $data['drive_time']));
    }

    public function getDriveTimeTxtAttr($value, $data)
    {
        if (!isset($data['drive_time'])) {
            return 0;
        }
        return date('Y-m-d', $data['drive_time']);
    }
}